package com.itzxx.huazhun.ui.testing

import android.Manifest
import android.os.Build
import android.text.TextUtils
import android.util.Log
import androidx.fragment.app.FragmentActivity
import cn.com.heaton.blelibrary.ble.model.BleDevice
import com.google.gson.Gson
import com.itzxx.huazhun.ui.testing.newbuild.TestingNewBuildActivity
import com.itzxx.huazhun.utils.DateUtil
import com.itzxx.huazhun.utils.UserCacheHelper
import com.itzxx.huazhun.utils.ble.BleHelper
import com.itzxx.huazhun.utils.ble.BleListener
import com.itzxx.library_base_ktx.base.viewmodel.BaseViewModel
import com.itzxx.library_base_ktx.callback.databind.StringObservableField
import com.itzxx.library_base_ktx.callback.livedata.StringLiveData
import com.itzxx.library_base_ktx.ext.util.loge
import com.itzxx.library_base_ktx.view.BaseDialog
import com.itzxx.library_base_ktx.view.MenuDialog
import com.permissionx.guolindev.PermissionX
import java.util.Timer
import java.util.TimerTask

class TestingViewModel : BaseViewModel() {

    val bleDeviceCheckLiveData = StringLiveData()

    private var checkBleDevice: BleDevice? = null
    private var mBleListener: BleListener? = null

    //开始时间
    val newTimeObservableField = StringObservableField()

    //采集时间
    val testingTimeObservableField = StringObservableField("90")
    val delayTimeObservableField = StringObservableField("0")
    val intervalTimeObservableField = StringObservableField("1")

    //定时器
    lateinit var timer: Timer

    //选择设备
    fun chooseBleBaseDevices() {
        val typeStrList = arrayListOf<String>()
        BleHelper.getBleBaseDevices().forEach { value ->
            typeStrList.add(value.bleName)
        }

        if (typeStrList.isEmpty()) {
            toast("未找到设备，请重新扫描！！！")
            return
        }

        baseContext.value?.let {  // 日期选择对话框
            MenuDialog.Builder(it)
                .setList(typeStrList)
                .setListener(object : MenuDialog.OnListener<String> {
                    override fun onSelected(dialog: BaseDialog?, position: Int, data: String) {
                        UserCacheHelper.putBleDevice(Gson().toJson( BleHelper.getBleBaseDevices().get(position)))
                        checkBleDevice = BleHelper.getBleBaseDevices().get(position)
                        bleDeviceCheckLiveData.postValue(checkBleDevice?.bleName)
                    }

                    override fun onCancel(dialog: BaseDialog?) {}
                })
                .show()
        }
    }


    fun stopTesting() {
        BleHelper.disconnect()
    }

    fun startTesting(value: String = "") {
        if (TextUtils.equals("未选中设备", bleDeviceCheckLiveData.value)) {
            toast("请选择设备")
        } else if (TextUtils.isEmpty(bleDeviceCheckLiveData.value)) {
            toast("请重新扫描蓝牙")
        } else {
            checkBleDevice?.let {
                if (it.isConnected) {
                    baseContext.value?.let { that ->
                        (that as FragmentActivity).runOnUiThread {
                            TestingNewBuildActivity.startActivity(
                                that,
//                                newTimeObservableField.get(),
                                testingTimeObservableField.get().toInt(),
                                delayTimeObservableField.get().toInt(),
                                intervalTimeObservableField.get().toInt()
                            )
                        }
                    }
                } else {
                    loadingChange.showDialog.postValue("设备连接中...")
                    BleHelper.connect(it)
                }
            }
        }
    }


    fun startScanBle() {
        baseContext.value?.let {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                PermissionX.init(baseContext.value as FragmentActivity).permissions(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_ADVERTISE,
                    Manifest.permission.BLUETOOTH_CONNECT
                ).request { allGranted, grantedList, deniedList ->
                    Log.e("grantedList", grantedList.toString())
                    Log.e("deniedList", deniedList.toString())
                    if (allGranted) {
                        if (BleHelper.isBleEnable(baseContext.value as FragmentActivity)) {
                            BleHelper.startScan()
                        } else {
                            toast("请先打开蓝牙，返回在重新扫描蓝牙")
                        }
                    } else {
                        toast("权限未同意，没办法使用该功能")
                    }
                }
            } else {
                PermissionX.init(baseContext.value as FragmentActivity).permissions(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                ).request { allGranted, grantedList, deniedList ->
                    Log.e("grantedList", grantedList.toString())
                    Log.e("deniedList", deniedList.toString())
                    if (allGranted) {
                        if (BleHelper.isBleEnable(baseContext.value as FragmentActivity)) {
                            BleHelper.startScan()
                        } else {
                            toast("请先打开蓝牙，返回在重新扫描蓝牙")
                        }
                    } else {
                        toast("权限未同意，没办法使用该功能")
                    }
                }
            }
        }
    }


    fun queryBleDevices() {
        checkBleDevice = BleHelper.getConnectBleDevice()

        if (checkBleDevice == null) {
            UserCacheHelper.getBleDevice()?.let {
                checkBleDevice = Gson().fromJson(it, BleDevice::class.java)
                BleHelper.initConnectBleDevicee(checkBleDevice)
            }
        }
        checkBleDevice?.let {
            bleDeviceCheckLiveData.postValue(it.bleName)
        }
    }

    override fun onResumeViewModel() {
        super.onPauseViewModel()
        queryBleDevices()
        checkBleDevice?.let {
            bleDeviceCheckLiveData.postValue(it.bleName)
        }

        mBleListener?.let {
            BleHelper.addBleListener(it)
        }
        timer = Timer()
        timer.schedule(onTimeTask(), 0, 1000)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            timer = Timer()
            timer.schedule(onTimeTask(), 0, 1000)
        } else {
            timer.cancel()
        }
    }

    override fun onPauseViewModel() {
        super.onPauseViewModel()
        mBleListener?.let {
            BleHelper.removeBleListener(it)
        }
        timer.cancel()
    }

    override fun onDestroyViewModel() {
        super.onDestroyViewModel()
        BleHelper.disconnect()
        checkBleDevice?.let {
            it.connectionState = BleDevice.DISCONNECT
            BleHelper.initConnectBleDevicee(it)
        }
    }

    override fun onCreateViewModel() {
        super.onCreateViewModel()
        mBleListener = object : BleListener() {
            override fun startBleScan() {
                super.startBleScan()
                loadingChange.showDialog.postValue("设备查找中...")
            }

            override fun onBleScanFirstDevice(device: BleDevice) {
                super.onBleScanFirstDevice(device)
                if (checkBleDevice != null && TextUtils.equals(checkBleDevice!!.bleAddress, device.bleAddress)) {
                    return
                }
                checkBleDevice = device
                bleDeviceCheckLiveData.postValue(device.bleName)
                UserCacheHelper.putBleDevice(Gson().toJson(device))
                loadingChange.dismissDialog.postValue(false)
            }

            override fun stopBleScan(devices: ArrayList<BleDevice>) {
                super.stopBleScan(devices)
                loadingChange.dismissDialog.postValue(false)
                "onStop".loge()
                if (checkBleDevice == null) {
                    bleDeviceCheckLiveData.postValue("未选中设备")
                }
            }

            override fun onScanFailed(errorMsg: String) {
                super.onScanFailed(errorMsg)
                "onScanFailed>>>>>${errorMsg}".loge()
            }

            override fun onEnableDataNotify(type: UByte, json: String) {
                super.onEnableDataNotify(type, json)
                "收到硬件数据>>>>>onChanged:${json}".loge()
            }

            override fun onNotifySuccess(device: BleDevice) {
                super.onNotifySuccess(device)
                baseContext.value?.let {
                    (it as FragmentActivity).runOnUiThread {
                        TestingNewBuildActivity.startActivity(
                            it,
//                            newTimeObservableField.get(),
                            testingTimeObservableField.get().toInt(),
                            delayTimeObservableField.get().toInt(),
                            intervalTimeObservableField.get().toInt()
                        )
                    }
                }
                loadingChange.dismissDialog.postValue(false)
            }

            override fun onConnectFail(errorMsg: String) {
                super.onConnectFail(errorMsg)
                toast(errorMsg)
                loadingChange.dismissDialog.postValue(false)
            }
        }
    }

    //定时器任务
    fun onTimeTask() = object : TimerTask() {
        override fun run() {
            newTimeObservableField.set(DateUtil.getYMDHMSStr(System.currentTimeMillis()))
        }
    }
}